package frontend;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import logs.LogFactory;

import org.apache.log4j.Logger;

import backend.Day;
import backend.InputValidation;
import backend.Session;
import backend.db.ConnectionManager;
import backend.db.ORM;
import backend.exceptions.ElementNotFoundException;

/**
 * Servlet implementation class CheckCourse
 */
public class CheckCourse extends HttpServlet {
  private static final Logger logger = LogFactory.getLog(CheckCourse.class);
  private static final long serialVersionUID = 1L;
  
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  @Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) {
    logger.debug("CheckCourse");
    final String username = request.getParameter("username");
    final String courseId = request.getParameter("courseId");
    final String courseName = request.getParameter("courseName");
    final String lecturerInCharge = request.getParameter("lecturerInCharge");
    final String moedA = request.getParameter("moedA");
    final String moedB = request.getParameter("moedB");
    final String description = request.getParameter("description");
    final String creditPoints = request.getParameter("creditPoints");
    final String capacity = request.getParameter("capacity");
    final String groupNum = request.getParameter("groupNum");
    final String numberOfSessions = request.getParameter("numberOfSessions");
    try {
      ORM.getCourseById(courseId);
      response.setStatus(HttpStatus.SC_OK + 5);
      return;
    } catch (final ElementNotFoundException e2) {
      // good
    }
    try {
      ORM.getCourseByName(courseName);
      response.setStatus(HttpStatus.SC_OK + 6);
      return;
    } catch (final ElementNotFoundException e2) {
      // good
    }
    if (!InputValidation.validateCourse(username, courseId, courseName, lecturerInCharge, moedA, moedB,
        description, creditPoints, capacity, groupNum)) {
      logger.debug("course didn't validate");
      response.setStatus(HttpStatus.SC_OK + 1);
      return;
    }
    final ArrayList<Session> sessions = new ArrayList<Session>();
    for (int i = 0; i < Integer.parseInt(numberOfSessions); i++) {
      final String teacher = request.getParameter("teacherOfSession" + i);
      final String classLocation = request.getParameter("classLocationOfSession" + i);
      final String day = request.getParameter("dayOfSession" + i);
      final String type = request.getParameter("typeOfSession" + i);
      final String start = request.getParameter("startOfSession" + i);
      final String duration = request.getParameter("durationOfSession" + i);
      if (!InputValidation.validateSession(courseId, day, start, duration, teacher, classLocation, type)) {
        logger.debug("session didn't validate");
        response.setStatus(HttpStatus.SC_OK + 2);
        return;
      }
      final boolean isLecture = type.equals("lecture") ? true : false;
      final Session s = new Session(courseId, Day.valueOf(day), Integer.parseInt(start),
          Integer.parseInt(duration), teacher, classLocation, isLecture);
      sessions.add(s);
    }
    try {
      int res = 0;
      if ((res = ORM.sessionsToAddAreValid(sessions, Integer.parseInt(groupNum))) > 0) {
        logger.debug("session to add wasn't valid: " + res);
        response.setStatus(HttpStatus.SC_OK + 2 + res);
        return;
      }
    } catch (final NumberFormatException e) {
      logger.error("parameter groupNum wasn't numeric. was: " + groupNum, e);
      try {
        response.sendError(HttpStatus.SC_BAD_REQUEST);
      } catch (final IOException e1) {
        logger.error("couldn't send error " + HttpStatus.SC_BAD_REQUEST, e1);
      }
      return;
    }
    final ConnectionManager cm = ORM.cp.captureConnection();
    try {
      for (int i = 0; i < sessions.size(); i++)
        ORM.addCourseSession(cm.getConn(), sessions.get(i));
      ORM.addCourse(cm.getConn(), username, courseId, courseName, lecturerInCharge, moedA, moedB,
          description, creditPoints, capacity, groupNum);
      ORM.addCourseSpace(cm.getConn(), courseName, Integer.parseInt(capacity));
      cm.getConn().commit();
    } catch (final Exception e1) {
      try {
        cm.getConn().rollback();
      } catch (final SQLException e) {
        logger.error("rollback failed", e);
      }
    } finally {
      ORM.cp.releaseConnection(cm);
    }
    logger.debug("course checked.");
  }
}
